
package com.joysuch.wwyt.mh.service.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;

import javax.transaction.Transactional;

import com.joysuch.wwyt.bp.entity.BpJob;
import com.joysuch.wwyt.core.bean.SimpleInfoBean;
import com.joysuch.wwyt.core.bean.SimpleSelectListBean;
import com.joysuch.wwyt.core.common.util.PageDataUtils;
import com.joysuch.wwyt.core.common.util.PageDataUtils.PageDataConvert;
import com.joysuch.wwyt.core.entity.BaseUser;
import com.joysuch.wwyt.core.repository.BaseUserDao;
import com.joysuch.wwyt.core.service.SimpleSelectListService;
import com.joysuch.wwyt.mh.bean.*;
import com.joysuch.wwyt.mh.bean.GlobalConfigBean.LevelConfig;
import com.joysuch.wwyt.mh.bean.MhAlarmRuleConfigBean.MonitoringTypeJobGroup;
import com.joysuch.wwyt.mh.entity.*;
import com.joysuch.wwyt.mh.entity.dsl.QMhAlarmRule;
import com.joysuch.wwyt.mh.entity.dsl.QMhAlarmRuleInformChannal;
import com.joysuch.wwyt.mh.entity.dsl.QMhAlarmRuleJob;
import com.joysuch.wwyt.mh.entity.dsl.QMhAlarmRuleUser;
import com.joysuch.wwyt.mh.entity.dsl.QMhInformChannel;
import com.joysuch.wwyt.mh.entity.dsl.QMhMonitoringPoint;
import com.joysuch.wwyt.mh.repository.*;
import com.joysuch.wwyt.mh.service.MhAlarmRuleService;
import com.querydsl.core.types.ExpressionUtils;
import com.querydsl.core.types.Predicate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

@Service
@Transactional
public class MhAlarmRuleServiceImpl implements MhAlarmRuleService {

    @Autowired
    private MhAlarmRuleDao dao;
    @Autowired
    private MhAlarmRuleJobDao mhAlarmRuleJobDao;
    @Autowired
    private MhAlarmRuleUserDao mhAlarmRuleUserDao;
    @Autowired
    private MhAlarmRuleInfoChannelDao infoChannelDao;
    @Autowired
    private MhInformChannelDao channelDao;
    @Autowired
    private MhMonitoringPointDao mhMonitoringPointDao;
    @Autowired
    private SimpleSelectListService simpleSelectListService;
    @Autowired
    private BaseUserDao userDao;
    @Autowired
    private MhAlarmConfigDao mhAlarmConfigDao;

    @Override
    public Page<MhAlarmRuleListBean> list(String name, String defaultConfig, Long monitoringTypeId, Pageable pageable) {
        pageable = PageDataUtils.addOrderByDesc(pageable, "id");
        Predicate p = prepareSearchCondition(name, monitoringTypeId, defaultConfig);

        Page<MhMonitoringPoint> all = p == null ? mhMonitoringPointDao.findAll(pageable)
                : mhMonitoringPointDao.findAll(p, pageable);
        List<MhAlarmRuleListBean> list = new ArrayList<>();
        for (MhMonitoringPoint mp : all) {
            MhAlarmRuleListBean bean = new MhAlarmRuleListBean();
            bean.setId(mp.getId());
            bean.setMonitoringTypeId(mp.getMhMonitoringType().getId());
            bean.setMinitoringTypeName(mp.getMhMonitoringType().getName());
            bean.setName(mp.getName());
            bean.setPointCode(mp.getPointCode());// 传感器编号
            List<MhAlarmRule> rules = dao.findByMonitoringPointId(mp.getId());
            if (rules.size() > 0) {
                bean.setDefaultConfig("N");
            } else {
                bean.setDefaultConfig("Y");
            }
            list.add(bean);
        }

        return new PageImpl<>(list, pageable, all.getTotalElements());
    }

    /**
     * @param name
     * @param monitoringTypeId
     * @return
     */
    protected Predicate prepareSearchCondition(String name, Long monitoringTypeId, String defaultConfig) {
        QMhMonitoringPoint mmp = QMhMonitoringPoint.mhMonitoringPoint;
        Predicate predicate1 = null;
        if (name != null) {
            predicate1 = ExpressionUtils.or(mmp.pointCode.contains(name), mmp.name.contains(name));
        }
        if (monitoringTypeId != null) {
            predicate1 = ExpressionUtils.and(predicate1, mmp.mhMonitoringType.id.eq(monitoringTypeId));
        }
        if (defaultConfig != null) {
            if ("Y".equals(defaultConfig)) {
                System.out.println(dao.findMonitorPointIdsHasRules());
                predicate1 = ExpressionUtils.and(predicate1, mmp.id.notIn(dao.findMonitorPointIdsHasRules()));
            } else {
                predicate1 = ExpressionUtils.and(predicate1, mmp.id.in(dao.findMonitorPointIdsHasRules()));
            }
        }
        return predicate1;
    }

    @Override
    public void add(MhAlarmRuleJobListBean mhAlarmRuleJob) {
        String[] deartLimit1 = mhAlarmRuleJob.getDeartLimit();
        Long[] jobId = mhAlarmRuleJob.getJobIds();
        Long[] ruleId = mhAlarmRuleJob.getRuleIds();
        if (ruleId.length > 0 && ruleId != null) {
            for (Long aLong : ruleId) {
                if (jobId.length >= 0 && jobId != null) {
                    for (Long aLong1 : jobId) {
                        MhAlarmRuleJob mhAlarmRuleJob1 = new MhAlarmRuleJob();
                        mhAlarmRuleJob1.setJobId(aLong1);
                        mhAlarmRuleJob1.setRuleId(aLong);
                        mhAlarmRuleJob1.setTenentId(mhAlarmRuleJob.getTenentId());
                        mhAlarmRuleJobDao.save(mhAlarmRuleJob1);
                    }
                }
            }
        }

    }

    @Override
    public void edits(MhAlarmRuleJobListBean alarmRuleJob) {
        Optional<MhAlarmRuleJob> byId = mhAlarmRuleJobDao.findById(alarmRuleJob.getId());
        QMhAlarmRuleJob mhAlarmRuleJob = QMhAlarmRuleJob.mhAlarmRuleJob;
        Predicate predicate = mhAlarmRuleJob.isNotNull();
        Long[] ruleIds = alarmRuleJob.getRuleIds();
        for (Long ruleId : ruleIds) {
            predicate = ruleId == null ? predicate : ExpressionUtils.and(predicate, mhAlarmRuleJob.ruleId.eq(ruleId));
            Iterable<MhAlarmRuleJob> all = mhAlarmRuleJobDao.findAll(predicate);
            if (all != null && !"".equals(all)) {
                for (MhAlarmRuleJob ruleJob : all) {
                    mhAlarmRuleJobDao.delete(ruleJob);
                }
            }
            Long[] jobId = alarmRuleJob.getJobIds();
            if (jobId.length >= 0 && jobId != null) {
                for (Long aLong : jobId) {
                    MhAlarmRuleJob mhAlarmRuleJob1 = new MhAlarmRuleJob();
                    mhAlarmRuleJob1.setJobId(aLong);
                    mhAlarmRuleJob1.setRuleId(ruleId);
                    mhAlarmRuleJob1.setTenentId(alarmRuleJob.getTenentId());
                    mhAlarmRuleJob1.setDeleteFlag("0");
                    mhAlarmRuleJobDao.save(mhAlarmRuleJob1);
                }
                QMhAlarmRule mhAlarmRule = QMhAlarmRule.mhAlarmRule;
                Predicate predicate1 = mhAlarmRule.isNotNull();
                predicate1 = alarmRuleJob.getRuleId() == null ? predicate1
                        : ExpressionUtils.and(predicate1, mhAlarmRule.id.eq(alarmRuleJob.getRuleId()));
                Iterable<MhAlarmRule> all1 = dao.findAll(predicate1);
                for (MhAlarmRule alarmRule : all1) {
                    alarmRule.setDeartLimit(alarmRuleJob.getDeartLimita());
                    alarmRule.setDefaultConfig(alarmRuleJob.getDefaultConfig()[0]);
                    dao.save(alarmRule);
                }

            }
        }
    }

    @Override
    public MhJobQueryBean getById(Long id, Pageable pageable) {
        QMhAlarmRuleJob mhAlarmRuleJob = QMhAlarmRuleJob.mhAlarmRuleJob;
        Predicate predicate = mhAlarmRuleJob.isNotNull();
        QMhAlarmRule mhAlarmRule = QMhAlarmRule.mhAlarmRule;
        Predicate predicate2 = mhAlarmRule.isNotNull();
        predicate2 = id == null ? predicate2 : ExpressionUtils.and(predicate2, mhAlarmRule.monitoringPointId.eq(id));
        predicate2 = 1 == 0 ? predicate2 : ExpressionUtils.and(predicate2, mhAlarmRule.level.eq(1));
        predicate2 = "N" == null ? predicate2 : ExpressionUtils.and(predicate2, mhAlarmRule.defaultConfig.like("N"));
        Iterable<MhAlarmRule> all2 = dao.findAll(predicate2);
        String JobId = "";
        String TypeId = "";
        String Channal = "";
        Integer level = 0;
        String deartLimit = "";
        String defaultConfig = "";
        for (MhAlarmRule alarmRule : all2) {
            deartLimit = alarmRule.getDeartLimit();
            defaultConfig = alarmRule.getDefaultConfig();
            predicate = alarmRule.getId() == null ? predicate
                    : ExpressionUtils.and(predicate, mhAlarmRuleJob.ruleId.eq(alarmRule.getId()));
            Page<MhAlarmRuleJob> all = mhAlarmRuleJobDao.findAll(predicate, pageable);
            QMhAlarmRuleInformChannal mhAlarmRuleInformChannal = QMhAlarmRuleInformChannal.mhAlarmRuleInformChannal;
            Predicate predicate1 = mhAlarmRuleInformChannal.isNotNull();
            predicate1 = id == null ? predicate1
                    : ExpressionUtils.and(predicate1, mhAlarmRuleInformChannal.ruleId.eq(id));
            Iterable<MhAlarmRuleInformChannal> all1 = infoChannelDao.findAll(predicate1);
            for (MhAlarmRuleJob job : all) {
                JobId += job.getJobId() + ",";
                level = alarmRule.getLevel();

                TypeId = job.getMonitoringTypeId() + ",";
                MhAlarmRule one1 = dao.getOne(job.getRuleId());
                deartLimit = one1.getDeartLimit();
                for (MhAlarmRuleInformChannal channal : all1) {
                    Channal = channal.getChannelId() + "";
                }
            }
        }
        if (JobId != null && !"".equals(JobId)) {
            JobId = JobId.substring(0, JobId.length() - 1);
        }
        if (TypeId != null && !"".equals(TypeId)) {
            TypeId = TypeId.substring(0, TypeId.length() - 1);
        }
        MhJobQueryBean mhJobQueryBean = new MhJobQueryBean();
        QMhAlarmRuleUser mhAlarmRuleUser = QMhAlarmRuleUser.mhAlarmRuleUser;
        Predicate predicates = mhAlarmRuleUser.isNotNull();
        predicates = id == null ? predicates : ExpressionUtils.and(predicates, mhAlarmRuleUser.ruleId.eq(id));
        Iterable<MhAlarmRuleUser> alls = mhAlarmRuleUserDao.findAll(predicates);
        String name = "";
        String ids = "";
        for (MhAlarmRuleUser alarmRuleUser : alls) {
            ids += alarmRuleUser.getUserId() + ",";
            name += userDao.getBaseUserNameById(alarmRuleUser.getUserId());
        }
        if (ids != null && !"".equals(ids)) {
            ids = ids.substring(0, ids.length() - 1);
        }
        if (name != null && !"".equals(name)) {
            name = name.substring(0, name.length() - 1);
        }
        mhJobQueryBean.setSpecifyUsers(ids);
        mhJobQueryBean.setSpecifyUsersName(name);
        mhJobQueryBean.setLevel(level);
        mhJobQueryBean.setChannal(Channal);
        mhJobQueryBean.setTypeId(TypeId);
        mhJobQueryBean.setJobId(JobId);
        mhJobQueryBean.setDeartLimit(deartLimit);
        mhJobQueryBean.setDefaultConfig(defaultConfig);
        return mhJobQueryBean;
    }

    @Override
    public MhJobQueryBean getById2(Long id, Pageable pageable) {
        QMhAlarmRuleJob mhAlarmRuleJob = QMhAlarmRuleJob.mhAlarmRuleJob;
        Predicate predicate = mhAlarmRuleJob.isNotNull();
        QMhAlarmRule mhAlarmRule = QMhAlarmRule.mhAlarmRule;
        Predicate predicate2 = mhAlarmRule.isNotNull();
        predicate2 = id == null ? predicate2 : ExpressionUtils.and(predicate2, mhAlarmRule.monitoringPointId.eq(id));
        predicate2 = 2 == 0 ? predicate2 : ExpressionUtils.and(predicate2, mhAlarmRule.level.eq(2));
        predicate2 = "N" == null ? predicate2 : ExpressionUtils.and(predicate2, mhAlarmRule.defaultConfig.like("N"));
        Iterable<MhAlarmRule> all2 = dao.findAll(predicate2);
        String JobId = "";
        String TypeId = "";
        String Channal = "";
        Integer level = 0;
        String deartLimit = "";
        String defaultConfig = "";
        for (MhAlarmRule alarmRule : all2) {
            deartLimit = alarmRule.getDeartLimit();
            defaultConfig = alarmRule.getDefaultConfig();
            predicate = alarmRule.getId() == null ? predicate
                    : ExpressionUtils.and(predicate, mhAlarmRuleJob.ruleId.eq(alarmRule.getId()));
            Page<MhAlarmRuleJob> all = mhAlarmRuleJobDao.findAll(predicate, pageable);
            QMhAlarmRuleInformChannal mhAlarmRuleInformChannal = QMhAlarmRuleInformChannal.mhAlarmRuleInformChannal;
            Predicate predicate1 = mhAlarmRuleInformChannal.isNotNull();
            predicate1 = id == null ? predicate1
                    : ExpressionUtils.and(predicate1, mhAlarmRuleInformChannal.ruleId.eq(id));
            Iterable<MhAlarmRuleInformChannal> all1 = infoChannelDao.findAll(predicate1);
            for (MhAlarmRuleJob job : all) {
                JobId += job.getJobId() + ",";
                level = alarmRule.getLevel();
                TypeId = job.getMonitoringTypeId() + ",";
                MhAlarmRule one1 = dao.getOne(job.getRuleId());
                deartLimit = one1.getDeartLimit();
                for (MhAlarmRuleInformChannal channal : all1) {
                    Channal = channal.getChannelId() + "";
                }
            }
        }
        if (JobId != null && !"".equals(JobId)) {
            JobId = JobId.substring(0, JobId.length() - 1);
        }
        if (TypeId != null && !"".equals(TypeId)) {
            TypeId = TypeId.substring(0, TypeId.length() - 1);
        }

        QMhAlarmRuleUser mhAlarmRuleUser = QMhAlarmRuleUser.mhAlarmRuleUser;
        Predicate predicates = mhAlarmRuleUser.isNotNull();
        predicates = id == null ? predicates : ExpressionUtils.and(predicates, mhAlarmRuleUser.ruleId.eq(id));
        Iterable<MhAlarmRuleUser> alls = mhAlarmRuleUserDao.findAll(predicates);

        MhJobQueryBean mhJobQueryBean = new MhJobQueryBean();
        String name = "";
        String ids = "";
        for (MhAlarmRuleUser alarmRuleUser : alls) {
            ids += alarmRuleUser.getUserId() + ",";
            name += userDao.getBaseUserNameById(alarmRuleUser.getUserId());
        }
        mhJobQueryBean.setSpecifyUsers(ids);
        mhJobQueryBean.setSpecifyUsersName(name);
        mhJobQueryBean.setLevel(level);
        mhJobQueryBean.setChannal(Channal);
        mhJobQueryBean.setTypeId(TypeId);
        mhJobQueryBean.setJobId(JobId);
        mhJobQueryBean.setDeartLimit(deartLimit);
        mhJobQueryBean.setDefaultConfig(defaultConfig);
        return mhJobQueryBean;
    }

    @Override
    public MhAlarmRuleConfigQueryBean global() {
        /*
         * saveOrUpdateConfig(level1,level1Config,1,null);
         * saveOrUpdateConfig(level2,level2Config,2,null);
         */
        MhAlarmRuleConfigQueryBean mhAlarmRuleConfigQueryBean = new MhAlarmRuleConfigQueryBean();

        List<SimpleSelectListBean> allJobs = simpleSelectListService.list(BpJob.class, "name");
        List<SimpleSelectListBean> allMonitoringTypes = simpleSelectListService.list(MhMonitoringType.class, "name");
        List<SimpleSelectListBean> allInformChannels = simpleSelectListService.list(MhAlarmRuleInformChannal.class,
                "channelId");
        mhAlarmRuleConfigQueryBean.setAllJobs(allJobs);
        mhAlarmRuleConfigQueryBean.setAllMonitoringTypes(allMonitoringTypes);
        return mhAlarmRuleConfigQueryBean;

    }

    @Override
    public List<MhJobQueryBean> globalJob(Long id) {
        List<MhJobQueryBean> list = new ArrayList<>(2);
        MhAlarmRule level1 = dao.findByDefaultConfigAndLevel("Y", 1);
        if (level1 == null) {
            level1 = createDefaultRule(1);
        }
        MhJobQueryBean level1Config = findLevelConfig(level1);
        MhAlarmRule level2 = dao.findByDefaultConfigAndLevel("Y", 2);
        if (level2 == null) {
            level2 = createDefaultRule(2);
        }
        MhJobQueryBean level2Config = findLevelConfig(level2);
        list.add(level1Config);
        list.add(level2Config);
        return list;
    }

    /**
     * @param level1
     * @return
     */
    protected MhJobQueryBean findLevelConfig(MhAlarmRule level1) {
        List<MhAlarmRuleJob> all = mhAlarmRuleJobDao.findByRuleId(level1.getId());
        String JobId = "";
        String TypeId = "";
        String channal = "";
        for (MhAlarmRuleJob job : all) {
            if (job != null) {
                JobId += job.getJobId() + ",";
                TypeId += job.getMonitoringTypeId() + ",";
            }
        }
        List<MhAlarmRuleInformChannal> all1 = infoChannelDao.findByRuleId(level1.getId());
        for (MhAlarmRuleInformChannal c : all1) {
            channal = c.getChannelId() + "";
        }
        if (JobId.length() > 0) {
            JobId = JobId.substring(0, JobId.length() - 1);
        }
        if (TypeId.length() > 0) {
            TypeId = TypeId.substring(0, TypeId.length() - 1);
        }
        MhJobQueryBean mhJobQueryBean = new MhJobQueryBean();
        mhJobQueryBean.setLevel(level1.getLevel());
        mhJobQueryBean.setChannal(channal);
        mhJobQueryBean.setTypeId(TypeId);
        mhJobQueryBean.setJobId(JobId);
        mhJobQueryBean.setDeartLimit(level1.getDeartLimit());
        return mhJobQueryBean;
    }

    private MhAlarmRule createDefaultRule(int level) {
        MhAlarmRule rule = new MhAlarmRule();
        rule.setLevel(level);
        rule.setDefaultConfig("Y");
        dao.save(rule);
        return rule;
    }

    @Override
    public void save(ArrayList<MhAlarmRuleJobListBean> list) {
        for (MhAlarmRuleJobListBean mhAlarmRuleJobListBean : list) {
            QMhAlarmRuleJob mhAlarmRuleJobs = QMhAlarmRuleJob.mhAlarmRuleJob;
            Predicate predicate = mhAlarmRuleJobs.isNotNull();
            predicate = mhAlarmRuleJobListBean.getRuleId() == null ? predicate
                    : ExpressionUtils.and(predicate, mhAlarmRuleJobs.ruleId.eq(mhAlarmRuleJobListBean.getRuleId()));
            Iterable<MhAlarmRuleJob> all = mhAlarmRuleJobDao.findAll(predicate);
            for (MhAlarmRuleJob alarmRuleJob : all) {
                mhAlarmRuleJobDao.delete(alarmRuleJob);
            }
        }
        for (MhAlarmRuleJobListBean mhAlarmRuleJob : list) {
            MhAlarmRuleJob mhAlarmRuleJob1 = new MhAlarmRuleJob();
            mhAlarmRuleJob1.setDeleteFlag("0");
            mhAlarmRuleJob1.setTenentId(mhAlarmRuleJob.getTenentId());
            mhAlarmRuleJob1.setJobId(mhAlarmRuleJob.getJobId());
            mhAlarmRuleJob1.setRuleId(mhAlarmRuleJob.getRuleId());
            mhAlarmRuleJobDao.save(mhAlarmRuleJob1);
            QMhAlarmRule mhAlarmRule = QMhAlarmRule.mhAlarmRule;
            Predicate predicate1 = mhAlarmRule.isNotNull();
            predicate1 = mhAlarmRuleJob1.getRuleId() == null ? predicate1
                    : ExpressionUtils.and(predicate1, mhAlarmRule.id.eq(mhAlarmRuleJob1.getRuleId()));
            Iterable<MhAlarmRule> all1 = dao.findAll(predicate1);
            for (MhAlarmRule alarmRule : all1) {
                alarmRule.setDeartLimit(mhAlarmRuleJob.getDeartLimita());
                alarmRule.setDefaultConfig(mhAlarmRuleJob.getDefaultConfig()[0]);
                dao.save(alarmRule);
            }
        }
    }

    @Override
    public void saveGlobalConfig(MhAlarmRuleConfigBean level1Config, MhAlarmRuleConfigBean level2Config) {
        MhAlarmRule level1 = dao.findByDefaultConfigAndLevel("Y", 1);
        MhAlarmRule level2 = dao.findByDefaultConfigAndLevel("Y", 2);
        saveOrUpdateConfig(level1, level1Config, 1, null);
        saveOrUpdateConfig(level2, level2Config, 2, null);
    }

    @Override
    public void updateSingleMonitoringPointConfig(Long monitoringPointId, MhAlarmRuleConfigBean level1Config,
                                                  MhAlarmRuleConfigBean level2Config) {
        MhAlarmRule level1 = dao.findByMonitoringPointIdAndLevel(monitoringPointId, 1);
        MhAlarmRule save1 = dao.save(level1);
        MhAlarmRule level2 = dao.findByMonitoringPointIdAndLevel(monitoringPointId, 2);

        MhAlarmRule save2 = dao.save(level2);
        saveOrUpdateConfig(save1, level1Config, 1, monitoringPointId);
        saveOrUpdateConfig(save2, level2Config, 2, monitoringPointId);
    }

    private void saveOrUpdateConfig(MhAlarmRule rule, MhAlarmRuleConfigBean level1Config, int level,
                                    Long monitoringPointId) {
        if (rule == null) {
            rule = new MhAlarmRule();
            rule.setDeartLimit(level1Config.getLimitDepart() ? "Y" : "N");
            rule.setDefaultConfig(level1Config.getDefaultConfig() ? "Y" : "N");
            rule.setLevel(level);
            if (monitoringPointId != null) {
                rule.setMonitoringPointId(monitoringPointId);
            }
            dao.save(rule);
        } else {
            rule.setDeartLimit(level1Config.getLimitDepart() ? "Y" : "N");
            dao.save(rule);
            // 先删除，再保存
            infoChannelDao.deleteByRuleId(rule.getId());
            mhAlarmRuleUserDao.deleteByRuleId(rule.getId());
            mhAlarmRuleJobDao.deleteByRuleId(rule.getId());
        }
        if (level1Config != null) {
            if (level1Config.getInformChannels() != null && level1Config.getInformChannels().size() > 0) {
                for (Long cid : level1Config.getInformChannels()) {
                    MhAlarmRuleInformChannal channal = new MhAlarmRuleInformChannal();
                    channal.setChannelId(cid);
                    channal.setRuleId(rule.getId());
                    infoChannelDao.save(channal);
                }
            }
            if (level1Config.getInformGroups() != null && level1Config.getInformGroups().size() > 0) {
                for (MhAlarmRuleConfigBean.MonitoringTypeJobGroup g : level1Config.getInformGroups()) {
                    MhAlarmRuleJob job = new MhAlarmRuleJob();
                    job.setRuleId(rule.getId());
                    job.setJobId(g.getJobId());
                    job.setMonitoringTypeId(g.getMonitoringTypeId());
                    mhAlarmRuleJobDao.save(job);
                }
            }
            if (level1Config.getSpecifyUsers() != null && level1Config.getSpecifyUsers().size() > 0) {
                for (Long uid : level1Config.getSpecifyUsers()) {
                    System.out.println(uid);
                    MhAlarmRuleUser user = new MhAlarmRuleUser();
                    user.setRuleId(rule.getId());
                    user.setUserId(uid);
                    mhAlarmRuleUserDao.save(user);
                }
            }

        }
    }

    @Override
    public GlobalConfigBean queryGlobalConfig() {
        GlobalConfigBean bean = new GlobalConfigBean();
        bean.setJobs(loadJobs());
        bean.setMonitoringTypes(loadTypes());
        bean.setLevel1Config(loadLevelConfig(1));
        bean.setLevel2Config(loadLevelConfig(2));
        return bean;
    }

    private LevelConfig loadLevelConfig(int level) {
        MhAlarmRule rule = dao.findByDefaultConfigAndLevel("Y", level);
        LevelConfig config = new LevelConfig();
        if (rule == null) {
            config.setChannels(Collections.EMPTY_LIST);
            config.setLimitDepart(false);
            config.setPoints(Collections.EMPTY_LIST);
        } else {
            config.setChannels(loadRuleChannels(rule.getId()));
            config.setLimitDepart("Y".equals(rule.getDeartLimit()));
            config.setPoints(loadJobSelections(rule.getId()));
        }
        return config;
    }

    private LevelConfig loadMonitorPointLevelConfig(Long monitorPointId, int level) {
        MhAlarmRule rule = dao.findByMonitoringPointIdAndLevel(monitorPointId, level);
        LevelConfig config = new LevelConfig();
        if (rule == null) {
            config.setChannels(Collections.EMPTY_LIST);
            config.setLimitDepart(false);
            config.setSelectJobs(Collections.EMPTY_LIST);
            config.setSelectUsers(Collections.EMPTY_LIST);
        } else {
            config.setChannels(loadRuleChannels(rule.getId()));
            config.setLimitDepart("Y".equals(rule.getDeartLimit()));
            List<Long[]> list = loadJobSelections(rule.getId());
            List<Long> selectJobs = PageDataUtils.convertListData(list, new PageDataConvert<Long, Long[]>() {

                @Override
                public Long convert(Long[] f) {
                    return f[1];
                }
            });
            config.setSelectJobs(selectJobs);
            config.setSelectUsers(loadSelectUsers(rule.getId()));
        }
        return config;
    }

    private List<SimpleInfoBean> loadSelectUsers(Long id) {
        Iterable<MhAlarmRuleUser> all = mhAlarmRuleUserDao.findAll(QMhAlarmRuleUser.mhAlarmRuleUser.ruleId.eq(id));
        List<SimpleInfoBean> list = new ArrayList<>(5);
        for (MhAlarmRuleUser user : all) {
            BaseUser bu = userDao.findById(user.getUserId()).orElse(null);
            if (bu != null) {
                SimpleInfoBean ub = new SimpleInfoBean();
                ub.setId(bu.getId());
                ub.setName(bu.getRealName());
                list.add(ub);
            }

        }
        return list;
    }

    private List<Long[]> loadJobSelections(Long id) {
        List<MhAlarmRuleJob> rules = mhAlarmRuleJobDao.findByRuleId(id);
        List<Long[]> re = new ArrayList<>(rules.size());
        for (MhAlarmRuleJob j : rules) {
            Long[] point = new Long[2];
            point[0] = j.getMonitoringTypeId();
            point[1] = j.getJobId();
            re.add(point);
        }
        return re;
    }

    private List<String> loadRuleChannels(Long ruleId) {
        List<MhAlarmRuleInformChannal> channels = infoChannelDao.findByRuleId(ruleId);
        if (channels.size() > 0) {
            List<String> list = new ArrayList<>(channels.size());
            for (MhAlarmRuleInformChannal c : channels) {
                MhInformChannel channel = channelDao.findById(c.getChannelId()).orElse(null);
                if (channel != null) {
                    list.add(channel.getCode());
                }
            }
            return list;
        }
        return Collections.EMPTY_LIST;
    }

    private List<SimpleInfoBean> loadTypes() {
        List<SimpleSelectListBean> list = simpleSelectListService.list(MhMonitoringType.class, "name");
        return PageDataUtils.convertListData(list, new PageDataConvert<SimpleInfoBean, SimpleSelectListBean>() {

            @Override
            public SimpleInfoBean convert(SimpleSelectListBean f) {
                SimpleInfoBean bean = new SimpleInfoBean();
                bean.setId(f.getValue());
                bean.setName(f.getLabel());
                return bean;
            }
        });
    }

    private List<SimpleInfoBean> loadJobs() {
        List<SimpleSelectListBean> list = simpleSelectListService.list(BpJob.class, "name");
        return PageDataUtils.convertListData(list, new PageDataConvert<SimpleInfoBean, SimpleSelectListBean>() {

            @Override
            public SimpleInfoBean convert(SimpleSelectListBean f) {
                SimpleInfoBean bean = new SimpleInfoBean();
                bean.setId(f.getValue());
                bean.setName(f.getLabel());
                return bean;
            }
        });
    }

    @Override
    public void updateGlobalConfig(GlobalConfigBean bean) {
        // 更新一级报警
        MhAlarmRule level1 = dao.findByDefaultConfigAndLevel("Y", 1);
        MhAlarmRuleConfigBean level1Config = convertToConfigBean(bean.getLevel1Config(), true);
        saveOrUpdateConfig(level1, level1Config, 1, null);
        // 更新二级报警
        MhAlarmRuleConfigBean level2Config = convertToConfigBean(bean.getLevel2Config(), true);
        saveOrUpdateConfig(dao.findByDefaultConfigAndLevel("Y", 2), level2Config, 2, null);
    }

    private MhAlarmRuleConfigBean convertToConfigBean(LevelConfig level1Config, boolean defaultConfig) {
        MhAlarmRuleConfigBean bean = new MhAlarmRuleConfigBean();
        bean.setDefaultConfig(defaultConfig);
        bean.setInformChannels(findChannelIdsByCodes(level1Config.getChannels()));
        bean.setLimitDepart(level1Config.isLimitDepart());
        if (!defaultConfig) {
            bean.setSpecifyUsers(PageDataUtils.convertListData(level1Config.getSelectUsers(),
                    new PageDataConvert<Long, SimpleInfoBean>() {

                        @Override
                        public Long convert(SimpleInfoBean f) {
                            return f.getId();
                        }
                    }));
        } else {
            bean.setInformGroups(convertToInformGroups(level1Config.getPoints()));
        }
        return bean;
    }

    private MhAlarmRuleConfigBean convertToConfigBean(LevelConfig level1Config, Long monitorPointId) {
        MhAlarmRuleConfigBean config = convertToConfigBean(level1Config, false);
        Long monitorTypeId = mhMonitoringPointDao.getOne(monitorPointId).getMhMonitoringType().getId();
        if (level1Config.getSelectJobs() != null && level1Config.getSelectJobs().size() > 0) {
            List<MonitoringTypeJobGroup> groups = PageDataUtils.convertListData(level1Config.getSelectJobs(),
                    new PageDataConvert<MonitoringTypeJobGroup, Long>() {

                        @Override
                        public MonitoringTypeJobGroup convert(Long f) {
                            MonitoringTypeJobGroup bean = new MonitoringTypeJobGroup();
                            bean.setMonitoringTypeId(monitorTypeId);
                            bean.setJobId(f);
                            return bean;
                        }

                    });
            config.setInformGroups(groups);
        }
        return config;
    }

    private List<Long> findChannelIdsByCodes(List<String> channels) {
        if (channels == null || channels.isEmpty()) {
            return Collections.EMPTY_LIST;
        }
        QMhInformChannel q = QMhInformChannel.mhInformChannel;
        Iterable<MhInformChannel> all = channelDao.findAll(q.code.in(channels));
        List<Long> list = new ArrayList<>(channels.size());
        for (MhInformChannel ch : all) {
            list.add(ch.getId());
        }
        return list;
    }

    private List<MonitoringTypeJobGroup> convertToInformGroups(List<Long[]> points) {
        return PageDataUtils.convertListData(points, new PageDataConvert<MonitoringTypeJobGroup, Long[]>() {

            @Override
            public MonitoringTypeJobGroup convert(Long[] f) {
                MonitoringTypeJobGroup bean = new MonitoringTypeJobGroup();
                bean.setMonitoringTypeId(f[0]);
                bean.setJobId(f[1]);
                return bean;
            }

        });
    }

    @Override
    public MonitorPointConfigBean queryMonitorPointConfig(Long monitorPointId) {
        MonitorPointConfigBean bean = new MonitorPointConfigBean();
        bean.setJobs(loadJobs());
        bean.setLevel1Config(loadMonitorPointLevelConfig(monitorPointId, 1));
        bean.setLevel2Config(loadMonitorPointLevelConfig(monitorPointId, 2));
        return bean;
    }

    @Override
    public LevelConfig globalTypeConfig(Long monitorPointId, Integer level) {
        LevelConfig config = loadLevelConfig(level);
        List<Long[]> points = config.getPoints();
        config.setPoints(null);
        List<Long> selectJobs = new ArrayList<>();
        // 查找和当前监测点类型相同的配置
        MhMonitoringPoint mhPoint = mhMonitoringPointDao.getOne(monitorPointId);
        Long typeId = mhPoint.getMhMonitoringType().getId();
        for (Long[] p : points) {
            if (p[0].equals(typeId)) {
                selectJobs.add(p[1]);
            }
        }
        config.setSelectJobs(selectJobs);
        return config;
    }

    @Override
    public void updateMonitorPointConfig(MonitorPointConfigBean bean) {
        // 更新一级报警
        MhAlarmRule level1 = dao.findByMonitoringPointIdAndLevel(bean.getMonitorPointId(), 1);
        MhAlarmRuleConfigBean level1Config = convertToConfigBean(bean.getLevel1Config(), bean.getMonitorPointId());
        saveOrUpdateConfig(level1, level1Config, 1, bean.getMonitorPointId());
        // 更新二级报警
        MhAlarmRuleConfigBean level2Config = convertToConfigBean(bean.getLevel2Config(), bean.getMonitorPointId());
        saveOrUpdateConfig(dao.findByMonitoringPointIdAndLevel(bean.getMonitorPointId(), 2), level2Config, 2,
                bean.getMonitorPointId());
    }

    /**
     * 保存二级报警配置
     *
     * @param bean
     * @return
     */
    @Override
    public MhAlarmConfig saveAlarmConfig(MhAlarmConfigBean bean) {
        MhAlarmConfig config = null;
        if (bean.getId() == null) {
            config = new MhAlarmConfig();
        } else {
            Optional<MhAlarmConfig> byId = mhAlarmConfigDao.findById(bean.getId());
            if (byId.isPresent()) {
                config = byId.get();
                config.setId(bean.getId());
            } else {
                config = new MhAlarmConfig();
            }
        }
        config.setState(bean.getState());
        return mhAlarmConfigDao.save(config);
    }

    /**
     * 查询二级报警配置
     *
     * @param id
     * @return
     */
    @Override
    public MhAlarmConfigBean getAlarmConfigById(Long id) {
        MhAlarmConfig config = mhAlarmConfigDao.findById(id).orElseThrow(() -> new IllegalArgumentException("二级报警配置不存在"));
        MhAlarmConfigBean bean = new MhAlarmConfigBean();
        bean.setId(config.getId());
        bean.setState(config.getState());
        if (config.getState() == 0) {
            bean.setStateName("开");
        } else if (config.getState() == 1) {
            bean.setStateName("关");
        }
        return bean;
    }

    @Override
    public List<MhAlarmConfigBean> getAlarmConfigList() {
        List<MhAlarmConfig> all = mhAlarmConfigDao.findAll();
        List<MhAlarmConfigBean> list = new ArrayList<>();
        if (!CollectionUtils.isEmpty(all)) {
            for (MhAlarmConfig config : all) {
                MhAlarmConfigBean bean = new MhAlarmConfigBean();
                BeanUtils.copyProperties(config, bean);
                if (config.getState() == 0) {
                    bean.setStateName("开");
                } else if (config.getState() == 1) {
                    bean.setStateName("关");
                }
                list.add(bean);
            }
        }
        return list;
    }

}
